package com.foreknow.springboot.service.Impl;

import com.foreknow.springboot.mapper.CartMapper;
import com.foreknow.springboot.mapper.OrderMapper;
import com.foreknow.springboot.mapper.OrderdetailetMapper;
import com.foreknow.springboot.po.Cart;
import com.foreknow.springboot.po.Orderdetailet;
import com.foreknow.springboot.po.Orders;
import com.foreknow.springboot.service.OrdersService;
import com.foreknow.springboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderdetailetMapper orderdetailetMapper;

    @Autowired
    private CartMapper cartMapper;


    @Override
    public int createOrders(Orders orders) {
        orders.setOrderDate(CommonUtil.getCurrentDate());
//        String date = CommonUtil.getCurrentDate();
        Cart cart = new Cart();
        cart.setBusinessId(orders.getBusinessId());
        cart.setUserId(orders.getUserId());
        List<Orderdetailet> orderdetailetList = new ArrayList<>();
        List<Cart> cartList = cartMapper.listCart(cart);
        orderMapper.createOrders(orders);
        int orderId = orders.getOrderId();
        for (Cart cart1:cartList) {
            Orderdetailet orderdetailet = new Orderdetailet();
            orderdetailet.setOrderId(orderId);
            orderdetailet.setFoodId(cart1.getFoodId());
            orderdetailet.setQuantity(cart1.getQuantity());
            orderdetailetList.add(orderdetailet);
        }
        orderdetailetMapper.saveOrderdetailet(orderdetailetList);
        cartMapper.removeCart(cart);
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        List<Orderdetailet> orderdetailetList = null;
        orderdetailetList = orderdetailetMapper.listOrderdetailet(orderId);
        Orders orders = orderMapper.getOrdersById(orderId);
        orders.setOrderdetailet(orderdetailetList);
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        List<Orders> ordersList = null;
        ordersList = orderMapper.listOrdersByUserId(userId);
        List<Orderdetailet> orderdetailetList = null;
        for (Orders orders:ordersList) {
            Integer orderId = orders.getOrderId();
            orderdetailetList = orderdetailetMapper.listOrderdetailet(orderId);
            orders.setOrderdetailet(orderdetailetList);
        }
        return ordersList;
    }
}
